#!/bin/bash
set -vx
# This script is used by KCS server to build and upload kernels.
# If repository REPO_ID exists, it pulls and checkouts to COMMIT.
# Environment variables can be set:
# REPO_DIR GS_BUCKET GS_PATH GS_CONFIG KCONFIG_OPTS KBUILD_ARCH

function install_kconfig () {
    if test -z "$KCONFIG_OPTS" ; then
	gce-xfstests install-kconfig --arch "$KBUILD_ARCH" || exit 1
    else
	local array=($(echo $KCONFIG_OPTS | sed -e 's/,/ /g'))

	gce-xfstests install-kconfig --arch "$KBUILD_ARCH" "${array[@]}" || exit 1
    fi
}

if test -z "$KBUILD_ARCH" ; then
    KBUILD_ARCH=$(dpkg --print-architecture)
fi
KBUILD_OPTS="$KBUILD_OPTS --arch $KBUILD_ARCH"
image=bzImage
archdir=x86_64
if test "$ARCH" = "arm64" ; then
	image=Image
	archdir=arm64
fi

if command -v ccache &> /dev/null /cache/ccache ; then
    export PATH="/usr/lib/ccache:$PATH"
    export CCACHE_DIR=/cache/ccache
fi

if test -z "$REPO_DIR"; then
    REPO_DIR="."
fi

if test -z "$GS_PATH"; then
    GS_PATH="gs://$GS_BUCKET/bzImage"
fi

if test -n "$GS_CONFIG" ; then
    if gsutil cp "$GS_CONFIG" "$REPO_DIR/.config" ; then
	if test $(stat -c %s "$REPO_DIR/.config") -gt 16384 ; then
	    make oldconfig || exit 1
	else
	    make olddefconfig || exit 1
	fi
    else
	install_kconfig
    fi
else
    install_kconfig
fi
KERNEL_PATH="$REPO_DIR/arch/$archdir/boot/$image"
DPKG_FLAGS=
if [[ $GS_PATH == *.deb ]]; then
    DPKG_FLAGS=--dpkg
    KERNEL_PATH="$REPO_DIR/linux-image.deb"
fi

status=1
trap "rm -f /run/kernel-building; exit \$status" EXIT HUP INT QUIT TERM
touch "$REPO_DIR/last-used" "$REPO_DIR/last-touched" /run/kernel-building
(cd "$REPO_DIR" ; time gce-xfstests kbuild $DPKG_FLAGS $KBUILD_OPTS) || exit 1
status=0
rm -f /run/kernel-building
gce-xfstests upload-kernel --kernel "$KERNEL_PATH" $GS_PATH
